﻿using System;
using System.Collections.Generic;
using System.Text;
using EnvDTE80;
using TSVNAddin.SVN;

namespace TSVNAddin.Core
{
	public class Repository
	{
		private readonly SolutionAdapter _SolutionAdapter;
		private readonly SVNClientAdapter _SVNClientAdapter;

		private string _LastWorkingRoot = string.Empty;
		private string _LastSolutionFileName = string.Empty;

		public Repository(SolutionAdapter dteAdapter, SVNClientAdapter svnClientAdapter)
		{
			_SolutionAdapter = dteAdapter;
			_SVNClientAdapter = svnClientAdapter;
		}

		public virtual string GetWorkingRoot()
		{
			string fileName = _SolutionAdapter.GetFileName();
			return FindRootByFileName(fileName);
		}

		public virtual bool IsActive()
		{
			if (!_SolutionAdapter.IsOpen())
				return false;

			if (GetWorkingRoot() == string.Empty)
				return false;

			return true;
		}

		public virtual bool Contains(string fileName)
		{
			if (!IsActive())
				return false;

			if (!fileName.ToLower().Contains(GetWorkingRoot()))
				return false;

			return true;
		}

		private string FindRootByFileName(string solutionFileName)
		{
			if (_LastSolutionFileName == solutionFileName)
				return _LastWorkingRoot;

			_LastSolutionFileName = solutionFileName;

			SVNInfoArgs info = _SVNClientAdapter.GetRepositoryInfo(solutionFileName);
			_LastWorkingRoot = BuildRoot(solutionFileName, info);

			return _LastWorkingRoot;
		}

		private string BuildRoot(string fileName, SVNInfoArgs info)
		{
			if (info == null)
				return string.Empty;

			RepositoryPathBuilder pathBuilder = new RepositoryPathBuilder();
			return pathBuilder.BuildPath(fileName, info.RootAddress, info.FileAddress);
		}
	}
}
